<template
  ><!---->
  <div id="transfer" style="margin:10px 0">
    <div class="demo-spin-col" v-if="showLoading">
      <Spin fix>
        <Icon type="ios-loading" size="28" class="demo-spin-icon-load"></Icon>
        <div>加载中...请稍后</div>
      </Spin>
    </div>
    <Spin size="large" fix v-if="spinShow">
      <Icon type="ios-loading" size="28" class="demo-spin-icon-load"></Icon>
      <div>移除中...请稍后</div>
    </Spin>
    <Row style="margin-bottom:10px;">
      小组：<Tag color="blue">{{ selectGroup.name }}</Tag>
    </Row>
    <Row v-if="selectedUsers.length > 0" style="margin:10px 0;">
      组员：
      <div style="display: flex; flex-wrap: wrap;align-items: center;">
        <Tag
          type="border"
          closable
          color="primary"
          v-for="user in selectedUsers"
          :key="user.userId"
          @on-close="removeGroupUser"
          :name="user.userId"
          >{{ user.userName }}</Tag
        >
        <Button type="error" @click="clearUsers" size="small">清空用户</Button>
      </div>
    </Row>
    <Transfer
      v-if="!showLoading"
      ref="userTransfer"
      :data="formatAllUsers"
      :list-style="listStyle"
      :target-keys="formatSelectedUsers"
      :render-format="render2"
      :filter-method="filterMethod"
      :operations="['移除', '添加']"
      filter-placeholder="请输入用户名、昵称搜索"
      :titles="['未选用户', '已选用户']"
      filterable
      @on-change="handleChange"
    ></Transfer>
  </div>
</template>

<script>
import {
  addGroupUser,
  delGroupUser,
  queryGroup,
  queryAllGroupUser
} from '../../api/group.js';
import { queryCompanyUsers } from '@/api/users.js';
import encryption from '@/libs/encryption.js';
import { mapMutations } from 'vuex';

export default {
  name: 'AccessTransfer',
  props: ['selectGroup','show','contentId'],
  data() {
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    return {
      spinShow: false,
      USER_ID: September.userId,
      USER_Name: September.nickname,
      listStyle: {
        width: '45%',
        height: '300px'
      },
      allSelectedUsers: [],
      selectDelUserList: [],
      expGroupList: [],
      allUsers: [],
      selectedUsers: [],
      index: 0,
      showLoading: false,
      drillUsers: [],
      loadingGroup: false,
      loadingRange: false,
      rangeList: [],
      rangeId: '',
      allDesignerList:[]
    };
  },
  filters: {},
  watch: {
    show: function(val) {
      if (val) {
        this.selectedUsers = this.selectGroup.accessGroupUsers;
        this.initTransferQuery();
        this.getCompanyUserList();
        this.getAllAccessGroupMember();
      }
    }
  },
  mounted() {
    if (this.show) {
      this.getCompanyUserList()
      this.getAllAccessGroupMember();
      this.selectedUsers = this.selectGroup.accessGroupUsers;
    }
  },
  computed: {
    formatSelectedUsers: function() {
      // 选中的用户的id列表
      return this.selectedUsers.map((user) => user.userId);
    },
    formatAllUsers: function() {
      let arr = this.allSelectedUsers.map((user) => user.userId); // 所有已经加入的用户
      let arr2 = this.selectedUsers.map((user) => user.userId); // 本团队已经选择的用户
      let arr3 = arr.filter((id) => !arr2.includes(id)); // 加入其他团队的用户
      let cArr = this.allDesignerList.filter((user) => !arr3.includes(user.id)); // 过滤掉加入其他团队的成员，本团队的成员虽然已加入，还是再要穿梭框中展示
      return cArr.map((user) => {
        return {
          key: user.id,
          label: user.nickname
        };
      });
    }
  },
  methods: {
    // ...mapMutations('compet', ['setRefreshChatRoom']),
    // 初始化使用，用于后续可选操作
    getAccessUserInfo() {
      this.getCompanyUserList();
    },
    // 单位人员列表
    getCompanyUserList() {
        // let role = this.type === 'apply' ? 'leader' : 'member';
        let params = {
            pageIndex: 1,
            pageSize: 1000000,
            order: 'desc',
            sortBy: 'created',
            type: 'designer',
            role: 'member' // leader
        };
        queryCompanyUsers(params)
            .then(({ code, data, message }) => {
                if (code === 1) {
                    this.allDesignerList = data.items;
                } else {
                }
            })
            .catch((err) => {});
    },
    // 指定接入组，查询组内已接入用户的列表
    getAccessGroupMember() {
      // getaccessgroupmember(this.selectGroup.id).then((data) => {
      //   if (data.code == 1) {
      //     this.selectedUsers = data.data.items || data.data;
      //   } else if (data.code == -2) {
      //     this.selectedUsers = [];
      //   } else {
      //     this.selectedUsers = [];
      //     this.$Message.warning(data.message);
      //   }
      // });
      queryGroup({
        pageIndex:1,
        pageSize:1,
        id:this.selectGroup.id,
        contentId:this.contentId
      }
      ).then((data) => {
          if (data.code == 1) {
              this.selectedUsers = data.data.items[0].accessGroupUsers;
          } else if (data.code == -2) {
              this.selectedUsers = [];
          } else {
              this.$Message.warning(data.message);
          }
      });
    },
    // 获取场景下所有的已接入用户
    getAllAccessGroupMember() {
      queryAllGroupUser(this.contentId).then((data) => {
        if (data.code == 1) {
          this.allSelectedUsers = data.data;
        } else if (data.code == -2) {
          this.allSelectedUsers = [];
        } else {
          this.allSelectedUsers = [];
          this.$Message.warning(data.message);
        }
      });
    },
    // 穿梭框过滤回调
    filterMethod(data, query) {
      return data.label.indexOf(query.trim()) > -1;
    },
    // 穿梭框数据有变化
    handleChange(targetKeys, direction, moveKeys) {
      if(direction == 'left') {
        this.delGroupUser(moveKeys);
      }else {
        addGroupUser(this.contentId,this.selectGroup.id, moveKeys.map(id => {
          return {
            userId:id,leader:false
          }
        })).then((data) => {
          if (data.code == 1) {
            this.$Message.info('添加成功');
            this.getAccessGroupMember();
            this.getAllAccessGroupMember();
          } else {
            this.$Message.warning(data.message);
          }
        });
      }
    },
    removeGroupUser(e,id){
      this.delGroupUser([id]);
    },
    delGroupUser(ids){
      delGroupUser(this.selectGroup.id, ids).then(res => {
        if(res.code == 1) {
          this.$Message.info('移除成功');
          this.getAccessGroupMember();
          this.getAllAccessGroupMember();
        } else {
          this.$Message.warning(res.message);
        }
      }).finally(() => {
        this.spinShow = false
      })
    },
    // 清空用户，直接接入空数据
    clearUsers() {
      let ids = this.selectedUsers.map((user) => user.userId)
      this.delGroupUser(ids);
    },
    // 穿梭框渲染回调
    render2(user) {
      return user.label;
    },
    initTransferQuery() {
      this.$refs.userTransfer.$refs.left.query = '';
      this.$refs.userTransfer.$refs.right.query = '';
    }
  }
};
</script>

<style scoped>
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.demo-spin-col {
  height: 200px;
  position: relative;
  border: 1px solid #eee;
}

.experimental-group {
  width: 150px;
}
.experimental-group >>> .ivu-select-selection {
  border-radius: 15px;
  border: 1px solid #cccccc !important;
  outline: 0;
}
.experimental-group >>> .ivu-select-selection:hover {
  border: 1px solid #1563C2  !important;
  box-shadow: 0px 0px 8px #1563C2 ;
}
.experimental-group >>> .ivu-select-selection:hover i {
  color: #1563C2 ;
}
</style>
